package com.ai;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import com.wedata.HttpUtils;

import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 人工智能
 * API 文档：https://open.manus.ai/docs
 * 运营后台：https://manus.im
 */
public class ManusAI {

    private static final String API_KEY = "sk-4Thyw9FQ6yKlwVx7bhWnaIoZUml760WzBxWBQdLqXXfb99V6Bn7Z_jVwVW9jkgT2wpLFNBYyvd-6qfo6LzSQ9styl5im";

    public static void main(String[] args) throws Exception {
        //downloadFile();
        getWebhookPublicKey();


        String publicKeyPEM = getWebhookPublicKey();
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyPEM);
        PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyBytes));

        Signature verifier = Signature.getInstance("SHA256withRSA");
        verifier.initVerify(publicKey);

        verifier.update("hello".getBytes());
        boolean bool = verifier.verify(publicKeyBytes);
        System.out.println(bool);
    }

    public static void createTask() {
        String prompt = "帮我生成一份适配电商 / APP / 本地生活场景的定制化转化漏斗数据，并补充各阶段流失原因分析？";
        String uri = "https://api.manus.ai/v1/tasks";
        JSONObject header = new JSONObject();
        header.put("API_KEY", API_KEY);
        header.put("Content-Type", "application/json");
        JSONObject body = new JSONObject();
        body.put("prompt", prompt);
        body.put("agentProfile", "manus-1.5");
        JSONObject response = HttpUtils.sendPost(uri, header, body);
        System.out.println(response);
        //{"task_url":"https://manus.im/app/kfYfXQWcFtbM3HtSb7te2o","task_id":"kfYfXQWcFtbM3HtSb7te2o","task_title":"Calculate Fibonacci Numbers Function"}
    }

    public static void downloadFile(){
        String url = "https://private-us-east-1.manuscdn.com/sessionFile/fESjJC53vtgpo8F8eb2Pz2/sandbox/processed/tRAPkJcOkqHEfeOiHziF8E_1763617877128_na1fn_L2hvbWUvdWJ1bnR1L3JlcG9ydA.md?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cHM6Ly9wcml2YXRlLXVzLWVhc3QtMS5tYW51c2Nkbi5jb20vc2Vzc2lvbkZpbGUvZkVTakpDNTN2dGdwbzhGOGViMlB6Mi9zYW5kYm94L3Byb2Nlc3NlZC90UkFQa0pjT2txSEVmZU9pSHppRjhFXzE3NjM2MTc4NzcxMjhfbmExZm5fTDJodmJXVXZkV0oxYm5SMUwzSmxjRzl5ZEEubWQiLCJDb25kaXRpb24iOnsiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE3OTg3NjE2MDB9fX1dfQ__&Key-Pair-Id=K2HSFNDJXOU9YS&Signature=myrjKZGuv2pOZ0DMwDRUBgSVoFL~PEucGjEX0LjDt2QEnUL5LoP7VEHmI1PutdOu44K8OfZ7E2k1FlDgSQ-TiZVCA0UR5J0nu5bwqriUgK1yNAAFlDgEm8yRdlDG~hsAZyJX6OExcRUxren~A0i0zCjv3TZiSwmdUnrU~mWcE6hoz0-YrhzUiWwF9Q5pDH-~SGyewgbdxnKsJdNRHn7s9hcEBAAEJlOuCu19Ojq5H4q3LHZ9cdbjxvb84fNcGne8~lP4lZ5b39v8ir4Z7rSAN6kT9QAAl~Z8sLB50LEcbvbLPQDkdEsUV1y0Se1vhLuMu46ouVAiF~SfVVydbOEUHA__";
        HttpUtil.downloadFile(url, "D:\\ideaSpace\\my-collect\\src\\main\\resources\\report.md");
    }

    public static void getTask() {
        String uri = "https://api.manus.ai/v1/tasks/kfYfXQWcFtbM3HtSb7te2o";
        Map<String, String> headers = new HashMap<>();
        headers.put("API_KEY", API_KEY);
        headers.put("Content-Type", "application/json");
        JSONObject response = HttpUtils.doGet(uri, headers);
        System.out.println(response);
        //{"metadata":{"task_url":"https://manus.im/app/kfYfXQWcFtbM3HtSb7te2o"},"created_at":"1763546151","credit_usage":23,"output":[{"role":"user","type":"message","content":[{"type":"output_text","text":"Write a function to calculate fibonacci numbers"}],"id":"pwJOtmqAjEFupB4Ps2c011","status":"completed"},{"role":"assistant","type":"message","id":"ByIKESoqqxKzbGPfhC5E1V","status":"completed"},{"role":"assistant","type":"message","content":[{"type":"output_text","text":"Got it! I'll write a Fibonacci function for you."}],"id":"qsf6MnjWf5C5zGhdrAgpSD","status":"completed"},{"role":"assistant","type":"message","content":[{"type":"output_text","text":"I've created a comprehensive Fibonacci calculator with multiple implementations. The file includes:\n\n**Four different approaches:**\n\n1. **Recursive** - Simple but inefficient for large numbers (O(2^n) complexity)\n2. **Iterative** - Fast and memory efficient (O(n) time, O(1) space) - **recommended for most cases**\n3. **Memoized** - Recursive with caching for better performance (O(n) complexity)\n4. **Generator** - Memory efficient for generating multiple Fibonacci numbers\n\nEach function includes proper documentation, error handling for negative inputs, and example usage. The test output shows all implementations working correctly, calculating the Fibonacci sequence where F(0)=0, F(1)=1, F(2)=1, F(3)=2, and so on.\n\nFor most practical purposes, I recommend using **fibonacci_iterative()** as it offers the best balance of simplicity, performance, and memory efficiency."},{"fileName":"fibonacci.py","mimeType":"text/x-python","type":"output_file","fileUrl":"https://private-us-east-1.manuscdn.com/sessionFile/kfYfXQWcFtbM3HtSb7te2o/sandbox/VVXrJDpmMBbE8JPUieimY0_1763546191849_na1fn_L2hvbWUvdWJ1bnR1L2ZpYm9uYWNjaQ.py?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cHM6Ly9wcml2YXRlLXVzLWVhc3QtMS5tYW51c2Nkbi5jb20vc2Vzc2lvbkZpbGUva2ZZZlhRV2NGdGJNM0h0U2I3dGUyby9zYW5kYm94L1ZWWHJKRHBtTUJiRThKUFVpZWltWTBfMTc2MzU0NjE5MTg0OV9uYTFmbl9MMmh2YldVdmRXSjFiblIxTDJacFltOXVZV05qYVEucHkiLCJDb25kaXRpb24iOnsiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE3OTg3NjE2MDB9fX1dfQ__&Key-Pair-Id=K2HSFNDJXOU9YS&Signature=L3loPTSIEHPNTGrKS8Kobc0ePfkcdBWKloA65zlni4PRogiUvWktR4XakPQxai~37U~dkIIAeez3pg92FYuWY65McguK~gvWB2Q2b-bsBUom8-LE1OdOrjAg2XXZH-NqxGd-ZLwJAqX23R663NhZjjzWcvw88WZmCu5PCAuyipQ6N~Xzj56aZ2OI9VkqhpCbAYXM-A1omUKP-ogVv-RQqri2omwBXPYaMmF06n0Z1FWQdezTl3SLOvvKYxYPyDPSyw0G95gsuAQf-q0rV2eCrYu80bCfybMwaHt7WUwdBwQ2If~N4pFQl4oyE50THUd0pMFcUuJb-fyVBlJr9TAIUg__"}],"id":"Kf5SUgez54p73qS8wo9zhD","status":"completed"}],"updated_at":"1763546192","model":"manus-1.5-adaptive","id":"kfYfXQWcFtbM3HtSb7te2o","object":"task","status":"completed"}
    }

    public static void createWebhook() {
        String uri = "https://api.manus.ai/v1/webhooks";
        JSONObject header = new JSONObject();
        header.put("API_KEY", API_KEY);
        header.put("Content-Type", "application/json");
        JSONObject body = new JSONObject();
        body.put("webhook", new JSONObject().put("url", "https://twedata.gymcity.com.cn/intelligent/api/manus/webhook"));
        JSONObject response = HttpUtils.sendPost(uri, header, body);
        System.out.println(response);
        //{"webhook_id":"XUwxRWfPF6VgcG89EikEJB"}
    }


    public static void deleteWebhook() {
        //XUwxRWfPF6VgcG89EikEJB
        String uri = "https://api.manus.ai/v1/webhooks/1234567890";
        JSONObject headers = new JSONObject();
        headers.put("API_KEY", API_KEY);
        JSONObject response = HttpUtils.sendDelete(uri, headers, new JSONObject());
        System.out.println(response);
    }

    public static void sentMessage() {
        JSONObject response = HttpUtils.sendPost("https://twedata.gymcity.com.cn/intelligent/api/manus/webhook",new JSONObject());
        System.out.println(response);
    }
    /**
     * 获取 Webhook 公钥
     */
    public static String getWebhookPublicKey() {
        String uri = "https://api.manus.ai/v1/webhook/public_key";
        Map<String, String> headers = new HashMap<>();
        headers.put("API_KEY", API_KEY);
        headers.put("Content-Type", "application/json");
        //JSONObject response1 = HttpUtils.doGet(uri);
        //JSONObject response2 = HttpUtils.doGet(uri, headers);//不需要带头部信息，也就是全是用同一把钥匙，（只有公钥解锁，没有私钥加密也就无法伪造信息，好像也没毛病）
        JSONObject response = new JSONObject("{\"public_key\":\"-----BEGIN PUBLIC KEY-----\\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4IYNOubHn/hUWYRYVuUs\\nRdpM7UJCUfoW+d8Ix81g37tJTFD3AsDU60NxmZAMI5rc8jL0eDyRbBJ8XkcAX3BQ\\n7V7A2LZKTwshCTK3uWZXRXgJL+XwkmdUBxESlizuFsHYyzWtjPOhvhsd7Gd/UJOR\\nRQsvN5UAcO6OAimGpkU6UB29Kl5MOXVs5SkjtmZe4N83GuaTo+xm7ciqRswcIhoj\\nQXZKyrnxiaiwq+1Nur9GWKEPv5xprMa3zPUhgg6Lw3ARbMrRY4Pjs+RlgEkwTFdz\\n35qEK5xWJDnvNvgIP5LUw+sUswIMbojSCF761i2tDQ7aVltCY3sriWNdvA2N24GC\\n8QIDAQAB\\n-----END PUBLIC KEY-----\\n\",\"created_at\":\"2025-11-20T01:24:25.919756792Z\",\"algorithm\":\"RSA-SHA256\"}");
        String publicKey = response.getStr("public_key").replaceAll("\\s", "");

        System.out.println(publicKey);

        return "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4IYNOubHn/hUWYRYVuUsRdpM7UJCUfoW+d8Ix81g37tJTFD3AsDU60NxmZAMI5rc8jL0eDyRbBJ8XkcAX3BQ7V7A2LZKTwshCTK3uWZXRXgJL+XwkmdUBxESlizuFsHYyzWtjPOhvhsd7Gd/UJORRQsvN5UAcO6OAimGpkU6UB29Kl5MOXVs5SkjtmZe4N83GuaTo+xm7ciqRswcIhojQXZKyrnxiaiwq+1Nur9GWKEPv5xprMa3zPUhgg6Lw3ARbMrRY4Pjs+RlgEkwTFdz35qEK5xWJDnvNvgIP5LUw+sUswIMbojSCF761i2tDQ7aVltCY3sriWNdvA2N24GC8QIDAQAB";
    }

}
